<template>
  <div class="recharge-record-page">
    <div class="page-header">
      <h2>充值记录</h2>
      <el-button @click="refreshData" :icon="Refresh">刷新</el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="充值金额">
          <el-input-number
            v-model="searchForm.minAmount"
            placeholder="最小金额"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 140px;"
          />
          <span style="margin: 0 8px;">-</span>
          <el-input-number
            v-model="searchForm.maxAmount"
            placeholder="最大金额"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 140px;"
          />
        </el-form-item>
        
        <el-form-item label="充值类型">
          <el-select v-model="searchForm.rechargeType" placeholder="请选择" clearable>
            <el-option label="手动充值" value="MANUAL" />
            <el-option label="自动充值" value="AUTO" />
            <el-option label="管理员充值" value="ADMIN" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="成功" :value="1" />
            <el-option label="失败" :value="0" />
            <el-option label="处理中" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        class="record-table"
      >
        <el-table-column prop="orderNo" label="订单号" min-width="180">
          <template #default="{ row }">
            <el-button type="text" @click="copyToClipboard(row.orderNo)">
              {{ row.orderNo }}
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="rechargeAmount" label="充值金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.rechargeAmount }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="余额变化" width="200" align="center">
          <template #default="{ row }">
            <div class="balance-change">
              <div class="before">充值前：¥{{ row.beforeBalance }}</div>
              <el-icon class="arrow-icon"><ArrowDown /></el-icon>
              <div class="after">充值后：¥{{ row.afterBalance }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="rechargeType" label="充值类型" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getRechargeTypeTagType(row.rechargeType)"
              size="small"
            >
              {{ getRechargeTypeName(row.rechargeType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="{ row }">
            {{ getPaymentMethodName(row.paymentMethod) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusTagType(row.status)"
              size="small"
            >
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        
        <el-table-column prop="createTime" label="充值时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 统计信息 -->
    <el-card class="statistics-card">
      <template #header>
        <div class="card-header">
          <el-icon><DataAnalysis /></el-icon>
          <span>充值统计</span>
        </div>
      </template>
      
      <div class="statistics-content" v-if="statistics">
        <div class="stat-item">
          <div class="stat-label">总充值金额</div>
          <div class="stat-value total">¥{{ statistics.totalAmount || '0.00' }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">总充值次数</div>
          <div class="stat-value count">{{ statistics.totalCount || 0 }}次</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">成功率</div>
          <div class="stat-value rate">{{ statistics.successRate || '0.00' }}%</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">平均充值</div>
          <div class="stat-value average">¥{{ statistics.averageAmount || '0.00' }}</div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Search, ArrowDown, DataAnalysis } from '@element-plus/icons-vue'
import request from '../utils/request'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const statistics = ref(null)

// 搜索表单
const searchForm = reactive({
  minAmount: null,
  maxAmount: null,
  rechargeType: '',
  status: null,
  dateRange: null
})

// 分页参数
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 获取充值记录数据
const fetchData = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.current,
      size: pagination.size
    }
    
    // 添加搜索条件
    if (searchForm.minAmount !== null) {
      params.minAmount = searchForm.minAmount
    }
    if (searchForm.maxAmount !== null) {
      params.maxAmount = searchForm.maxAmount
    }
    if (searchForm.rechargeType) {
      params.rechargeType = searchForm.rechargeType
    }
    if (searchForm.status !== null) {
      params.status = searchForm.status
    }
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startTime = searchForm.dateRange[0]
      params.endTime = searchForm.dateRange[1]
    }
    
    const response = await request.get('/user/recharge/records', { params })
    const result = response.data
    
    tableData.value = result.records || []
    pagination.total = result.total || 0
    
    // 计算统计信息
    calculateStatistics()
  } catch (error) {
    console.error('获取充值记录失败:', error)
    ElMessage.error('获取充值记录失败')
  } finally {
    loading.value = false
  }
}

// 计算统计信息
const calculateStatistics = () => {
  if (!tableData.value || tableData.value.length === 0) {
    statistics.value = {
      totalAmount: '0.00',
      totalCount: 0,
      successRate: '0.00',
      averageAmount: '0.00'
    }
    return
  }
  
  const successRecords = tableData.value.filter(record => record.status === 1)
  const totalAmount = successRecords.reduce((sum, record) => sum + parseFloat(record.rechargeAmount || 0), 0)
  const totalCount = tableData.value.length
  const successCount = successRecords.length
  const successRate = totalCount > 0 ? (successCount / totalCount * 100) : 0
  const averageAmount = successCount > 0 ? (totalAmount / successCount) : 0
  
  statistics.value = {
    totalAmount: totalAmount.toFixed(2),
    totalCount: totalCount,
    successRate: successRate.toFixed(2),
    averageAmount: averageAmount.toFixed(2)
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = null
    } else if (typeof searchForm[key] === 'number') {
      searchForm[key] = null
    } else {
      searchForm[key] = ''
    }
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (newSize) => {
  pagination.size = newSize
  pagination.current = 1
  fetchData()
}

const handleCurrentChange = (newPage) => {
  pagination.current = newPage
  fetchData()
}

// 刷新数据
const refreshData = () => {
  fetchData()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取充值类型名称
const getRechargeTypeName = (type) => {
  switch (type) {
    case 'MANUAL': return '手动充值'
    case 'AUTO': return '自动充值'
    case 'ADMIN': return '管理员充值'
    default: return type || '未知'
  }
}

// 获取充值类型标签类型
const getRechargeTypeTagType = (type) => {
  switch (type) {
    case 'MANUAL': return 'primary'
    case 'AUTO': return 'success'
    case 'ADMIN': return 'warning'
    default: return 'info'
  }
}

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  switch (method) {
    case 'BALANCE': return '余额支付'
    case 'ALIPAY': return '支付宝'
    case 'WECHAT': return '微信支付'
    default: return method || '未知'
  }
}

// 获取状态名称
const getStatusName = (status) => {
  switch (status) {
    case 1: return '成功'
    case 0: return '失败'
    case 2: return '处理中'
    default: return '未知'
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'danger'
    case 2: return 'warning'
    default: return 'info'
  }
}

// 复制到剪贴板
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('订单号已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.recharge-record-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.record-table {
  width: 100%;
}

.amount-text {
  font-weight: 600;
  color: #67c23a;
}

.balance-change {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
}

.before {
  color: #909399;
  margin-bottom: 2px;
}

.arrow-icon {
  color: #409eff;
  margin: 2px 0;
}

.after {
  color: #67c23a;
  font-weight: 600;
  margin-top: 2px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.statistics-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #333;
}

.card-header .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.statistics-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-value.total {
  color: #67c23a;
}

.stat-value.count {
  color: #409eff;
}

.stat-value.rate {
  color: #e6a23c;
}

.stat-value.average {
  color: #f56c6c;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .statistics-content {
    grid-template-columns: 1fr;
  }
}
</style> 